package bl.controller;

import java.util.ArrayList;

import database.factory.BookDataFactory;
import database.factory.BookDataFactoryImpl;
import database.service.BookDataService;

import po.BookPO;
import vo.BookVO;
import vo.SearchKeyVO;

import bl.domain.BookSearchByKey;
import bl.service.BookSearchByKeyBLService;

public class BookSearchByKeyController implements BookSearchByKeyBLService {

	private BookSearchByKey bookSearchByKey;

	public BookSearchByKeyController() {
		bookSearchByKey = new BookSearchByKey();
	}
	
	private void init() {
		BookDataFactory bookDataFactory = new BookDataFactoryImpl();
		BookDataService bookDataService = bookDataFactory.getBookDataService();
		bookDataService.load();
		bookSearchByKey.setBookItr(bookDataService.getIterator());
	}

	@Override
	public ArrayList<BookVO> directSearch(String key) {
		init();
		ArrayList<BookVO> bookList = new ArrayList<BookVO>();
		String[] keySplit = key.toLowerCase().split(" ");
		while (bookSearchByKey.getBookItr().hasNext()) {
			BookPO book = bookSearchByKey.getBookItr().next();
			String description = book.getDescription().toLowerCase();
			boolean notFount = false;
			for (int i = 0; i < keySplit.length; i++) {
				if (!description.contains(keySplit[i])) {
					notFount = true;
					break;
				}
			}

			if (notFount) {
				continue;
			}
			bookList.add(new BookVO(book));
		}
		return bookList;
	}

	@Override
	public ArrayList<BookVO> advanceSearch(SearchKeyVO key) {
		init();
		ArrayList<BookVO> bookList = new ArrayList<BookVO>();
		while (bookSearchByKey.getBookItr().hasNext()) {
			BookPO book = bookSearchByKey.getBookItr().next();
			boolean nameCheck = book.getName().toLowerCase()
					.contains(key.getName().toLowerCase())
					|| key.getName().length() == 0;
			boolean authorCheck = book.getAuthor().toLowerCase()
					.contains(key.getAuthor().toLowerCase())
					|| key.getAuthor().length() == 0;
			boolean pressCheck = book.getPress().toLowerCase()
					.contains(key.getPress().toLowerCase())
					|| key.getPress().length() == 0;
			boolean publishingYearCheck = book.getPublishingYear() == key
					.getPublishingYear() || key.getPublishingYear() == 0;
			boolean isFound = nameCheck && authorCheck && pressCheck
					&& publishingYearCheck;

			if (!isFound) {
				continue;
			}
			bookList.add(new BookVO(book));
		}
		return bookList;
	}

}
